package leetcode.code0692;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;

import leetcode.IDebug;

public class Solution implements IDebug {

	public List<String> topKFrequent(String[] words, int k) {
		Map<String, Integer> map = new HashMap<>();
		for (String word : words) {
			map.put(word, map.getOrDefault(word, 0) + 1);
		}
		PriorityQueue<Object[]> queue = new PriorityQueue<>((a, b) -> {
			String word1 = (String) a[0];
			String word2 = (String) b[0];
			int num1 = (int) a[1];
			int num2 = (int) b[1];
			if (num1 == num2) {
				return word2.compareTo(word1);
			}
			return num1 - num2;
		});
		for (Map.Entry<String, Integer> entry : map.entrySet()) {
			queue.add(new Object[] { entry.getKey(), entry.getValue() });
			if (queue.size() > k) {
				queue.poll();
			}
		}
		List<String> ans = new ArrayList<>();
		while (!queue.isEmpty()) {
			ans.add(0, (String) queue.poll()[0]);
		}
		return ans;
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
